<template>
  <div class="processInfo" v-loading="openProcessLoading">
    <span> 欢迎使用考勤分析工具！ </span>
    <!-- <div style="display:flex; width:900px;margin:100px auto;"> -->
    <div class="block">
      <span class="demonstration">考勤日查询范围: </span>
      <el-date-picker
        v-model="dateRangeArr"
        type="daterange"
        range-separator="To"
        start-placeholder="Start date"
        end-placeholder="End date"
      >
      </el-date-picker>
    </div>
    <div>
      <span class="demo-input-label"
        ><font color="red">*</font> 请输入工号:</span
      >
      <el-input placeholder="请输入工号" v-model="inputModel.workNo"></el-input
      ><br />

      <font color="red">*</font> 请输入token:
      <el-input placeholder="请输入token" v-model="inputModel.token"></el-input
      ><br />
      <el-button type="primary" @click="query">查询</el-button>
      <el-button type="primary" @click="clear">清除查询条件</el-button>
      <el-button type="primary" @click="clearPage">清除页面数据</el-button>
    </div>

    <div>
      <div class="block">
        <span class="demonstration">单据申请时间查询范围: </span>
        <el-date-picker
          v-model="requestDateRangeArr"
          type="daterange"
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
        >
        </el-date-picker>
      </div>
      请选择单据类型:
      <el-select v-model="selectedValue" placeholder="请选择单据类型">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option> </el-select
      ><br />
      <el-button type="primary" @click="queryApplys">查询单据</el-button>
    </div>
    <hr />
    <el-table :data="tableData" style="width: 100%">
      <!--       <el-table-column prop="userId" label="userId" width="180">
      </el-table-column> -->
      <!--       <el-table-column prop="chineseName" label="chineseName" width="180">
      </el-table-column> -->
      <el-table-column prop="requestNo" label="requestNo" width="180">
      </el-table-column>
      <!--       <el-table-column prop="employeeNo" label="employeeNo" width="180">
      </el-table-column>
      <el-table-column prop="posiName" label="posiName" width="180">
      </el-table-column>
      <el-table-column prop="orgCode" label="orgCode" width="180">
      </el-table-column>
      <el-table-column prop="orgName" label="orgName" width="180">
      </el-table-column> -->
      <el-table-column prop="requestId" label="requestId" width="180">
      </el-table-column>
      <el-table-column prop="requestType" label="requestType" width="180">
      </el-table-column>
      <el-table-column
        prop="approvalState"
        label="approvalState(-1-作废，0-待提交，1-审批中，2-审批通过，3-审批不通过)"
        width="180"
      >
      </el-table-column>
      <el-table-column prop="requestDate" label="requestDate" width="180">
      </el-table-column>
      <el-table-column prop="startTime" label="startTime" width="180">
      </el-table-column>
      <el-table-column prop="endTime" label="endTime" width="180">
      </el-table-column>
      <el-table-column prop="hours" label="hours" width="180">
      </el-table-column>
      <el-table-column prop="actualHours" label="actualHours" width="180">
      </el-table-column>
    </el-table>
    <hr />
    <div class="timeLineTitle">
      <div class="timeLineItem">
        <div class="finish timeLineStatus"></div>
        <div>实际打卡点</div>
      </div>
      <div class="timeLineItem">
        <div class="being timeLineStatus"></div>
        <div>实际上下班点</div>
      </div>
      <div class="timeLineItem">
        <div class="waiting timeLineStatus"></div>
        <div>规定上下班点</div>
      </div>
      <div class="timeLineItem">
        <div class="timeOut timeLineStatus"></div>
        <div>C点</div>
      </div>
    </div>

    <el-timeline
      style="margin-left: 100px; margin-top: 10px;"
      id="timeLineDate"
    >
      <el-timeline-item
        v-for="(activity, index) in activities"
        :key="index"
        icon="el-icon-timer"
        type="primary"
        size="large"
        :timestamp="activity.timestamp"
        placement="top"
      >
        <div style="display:flex;">
          <timeLine :timeLineList="activity.timeLineList"></timeLine>
        </div>
      </el-timeline-item>
    </el-timeline>
  </div>
</template>

<script>
import timeLine from "../timeline/Timeline.vue";
export default {
  name: "HomePage",
  components: { timeLine },
  data() {
    return {
      tableData: [],
      options: [
        {
          value: "7",
          label: "加班单",
        },
        {
          value: "0",
          label: "调休单",
        },
        {
          value: "9",
          label: "外勤",
        },
        /*         {
          value: "Option4",
          label: "Option4",
        }, */
        {
          value: "",
          label: "不限",
        },
      ],
      selectedValue: "",
      dateRangeArr: [],
      requestDateRangeArr: [],
      inputModel: {
        workNo: "",
        token:
          "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJHVDA1NjY5OCIsInVzZXJfbmFtZSI6IkdUMDU2Njk4IiwiX3VzZXJfbmFtZSI6Ium7juWtkOWBpSIsImV4cCI6MTYyNzgwMjMyMCwidXNlcklkIjoiZWExMDZlYjcwZmJkYWJmOTQ5ODMyNjY2ZjM4NTU3NWIifQ.9uFs567wmrzLYErYLeTNYaEthbR_vs6Bfv2MgI2JBec",
        userId: "", // 通过接口获取
        endDateStr: "",
        startDateStr: "",
      },
      openProcessLoading: false,
      activities: [
        /*   {
          timestamp: "4月1日",
          timeLineList: [
            {
              status: "",
              timestamp: "10：00",
              info: "BOSS账单",
              timeLineBranch: [
                { timestamp: "10:00", status: "being", info: "BOSS账单" },
                {
                  timestamp: "12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
                {
                  timestamp: "4月30日 12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
              ],
            },
            {
              status: "wating",
              timestamp: "12：00",
              info: "入会",
            },
            {
              status: "finish",
              timestamp: "13：00",
              info: "BOSS收入划拨",
            },
            {
              status: "wating",
              timestamp: "12：00",
              info: "入会",
            },
            {
              status: "finish",
              timestamp: "13：00",
              info: "BOSS收入划拨",
            },
          ],
        }, */
        /*  {
          timestamp: "4月3日",
          timeLineList: [
            {
              status: "finish",
              timestamp: "13：00",
              info: "工作室更名为：西安拓美网络科技有限公司3",
            },
            {
              status: "finish",
              timestamp: "14：00",
              info: "工作室更名为：西安拓美网络科技有限公司4",
              timeLineBranch: [
                { timestamp: "4月1日", status: "timeOut", info: "佣金结算" },
                { timestamp: "4月1日", status: "timeOut", info: "z端用户结算" },
                { timestamp: "10:00", status: "being", info: "BOSS账单" },
                {
                  timestamp: "12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
                {
                  timestamp: "4月30日 12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
              ],
            },
            {
              status: "finish",
              timestamp: "16：00",
              info: "工作室更名为：西安拓美网络科技有限公司5",
            },
            {
              status: "finish",
              timestamp: "18：00",
              info: "工作室更名为：西安拓美网络科技有限公司6",
            },
            {
              status: "finish",
              timestamp: "16：00",
              info: "工作室更名为：西安拓美网络科技有限公司5",
            },
            {
              status: "finish",
              timestamp: "18：00",
              info: "工作室更名为：西安拓美网络科技有限公司6",
            },
          ],
        }, */
        {
          timestamp: "4月5日",
          timeLineList: [
            {
              status: "finish",
              timestamp: "16：00",
              info: "占个坑",
            },
            {
              status: "finish",
              timestamp: "18：00",
              info: "占个坑",
            },
          ],
        },
        /*  {
          timestamp: "4月6日",
          timeLineList: [
            {
              status: "finish",
              timestamp: "20:00",
              info: "工作室更名为：西安拓美网络科技有限公司03",
            },
            {
              status: "finish",
              timestamp: "22:00",
              info: "工作室更名为：西安拓美网络科技有限公司02",
            },
            {
              status: "finish",
              timestamp: "2016-10-6",
              info: "工作室更名为：西安拓美网络科技有限公司01",
              timeLineBranch: [
                { timestamp: "4月1日", status: "timeOut", info: "z端用户结算" },
                { timestamp: "10:00", status: "being", info: "BOSS账单" },
                {
                  timestamp: "12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
                {
                  timestamp: "4月30日 12:00",
                  status: "wating",
                  info: "CB用户资料下载",
                },
              ],
            },
            {
              status: "being",
              timestamp: "20:00",
              info: "工作室更名为：西安拓美网络科技有限公司03",
            },
            {
              status: "finish",
              timestamp: "22:00",
              info: "工作室更名为：西安拓美网络科技有限公司02",
            },
            {
              status: "finish",
              timestamp: "2016-10-6",
              info: "工作室更名为：西安拓美网络科技有限公司01",
            },
            {
              status: "finish",
              timestamp: "20:00",
              info: "工作室更名为：西安拓美网络科技有限公司03",
            },
            {
              status: "finish",
              timestamp: "20:00",
              info: "工作室更名为：西安拓美网络科技有限公司03",
            },
          ],
        }, */
      ],
    };
  },
  created() {
    // do
  },
  methods: {
    getUserInfo() {
      let workNo = this.inputModel.workNo;
      let url = this.$Url.serviceUrl.queryUserList + "?workNum=" + workNo;
      return new Promise((resolve, reject) => {
        this.$get(url)
          .then((res) => resolve(res))
          .catch((res) => {
            reject(res);
          });
      });
    },
    // do
    getAttendanceList() {
      /*  let url = this.$Url.serviceUrl.queryAttendanceList;
      let params = {
        isAll: true,
        limit: 10,
        order: "DESC",
        page: 1,
        params: {
          endDateStr: "2021-06-10",
          startDateStr: "2021-06-07",
          state: "",
          userId: "02c7360fa03b45d0d28df3145b2acb69",
        },
      };
      this.$post(url, params)
        .then((res) => {
          console.log(res);
          this.$cookies.set("res", JSON.stringify(res));
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            let list = data.result.list;
            list.sort(this.sortAll("attendanceDate", true));
            list.forEach((element) => {
              console.log(element);
              let item = this.timelineItemTpl();
              let suffix = element.scheduleResultId ? "工作日" : "休息日";
              item.timestamp =
                this.$moment(element.attendanceDate).format("YYYY-MM-DD") +
                suffix;
              item.timeLineList.push({
                status: "being",
                timestamp: element.startTime,
                info: "实际上班点",
              });
              item.timeLineList.push({
                status: "being",
                timestamp: element.endTime,
                info: "实际下班点",
              });
              item.timeLineList.push({
                status: "waiting",
                timestamp: element.originalStartTime,
                info: "规定上班点",
              });
              item.timeLineList.push({
                status: "waiting",
                timestamp: element.originalEndTime,
                info: "规定下班点",
              });
              let punchRecords = element.punchRecord.split(",");
              punchRecords.forEach((rec, idx) => {
                item.timeLineList.push({
                  status: "finish",
                  timestamp: rec,
                  info: "打卡点" + idx,
                });
              });
              // 查询该班值的C点
              if (element.scheduleResultId) {
                this.queryBanZhi(element.scheduleResultId, item);
              }
              this.activities.push(item);

              console.log("排序前:", item.timeLineList);
              item.timeLineList.sort(this.sortAll("timestamp", true));
              console.log("排序后:", item.timeLineList);
            });
          }
        })
        .catch((res) => {
          console.log(res);
          this.openProcessLoading = false;
        }); */
      this.inputModel.startDateStr = this.$moment(this.dateRangeArr[0]).format(
        "YYYY-MM-DD"
      );
      this.inputModel.endDateStr = this.$moment(this.dateRangeArr[1]).format(
        "YYYY-MM-DD"
      );
      console.log(this.inputModel);
      return new Promise((resolve, reject) => {
        let url = this.$Url.serviceUrl.queryAttendanceList;
        let params = {
          isAll: true,
          limit: 10,
          order: "DESC",
          page: 1,
          params: {
            endDateStr: this.inputModel.endDateStr,
            startDateStr: this.inputModel.startDateStr,
            state: "",
            userId: this.inputModel.userId,
          },
        };
        this.$post(url, params)
          .then((res) => resolve(res))
          .catch((res) => reject(res));
      });
    },
    queryBanZhi(scheduleResultIdItemMap) {
      /*  let url = this.$Url.serviceUrl.queryBanZhi + scheduleResultId;
     this.$get(url)
        .then((res) => {
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            console.log(data);
            let result = data.result;
            if (result) {
              item.timeLineList.push({
                status: "timeOut",
                timestamp: result.endEffTime,
                info: "下班C点",
              });
              item.timeLineList.push({
                status: "timeOut",
                timestamp: result.startEffTime,
                info: "上班C点",
              });
            }
          }
        })
        .catch((res) => {
          console.log(res);
          this.openProcessLoading = false;
        }); */

      return new Promise((resolve, reject) => {
        resolve(scheduleResultIdItemMap);
        console.log(reject);
      });
    },
    query() {
      if (!this.validateParam()) {
        return;
      }
      this.$cookies.set("token", this.inputModel.token);
      this.getUserInfo()
        .then((res) => {
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            let records = data.result.records;
            if (records && records.length > 0) {
              let user = records[0];
              this.inputModel.userId = user.id;
            } else {
              this.$message.error("查无此人记录!");
            }
          }
          return this.getAttendanceList();
        })
        .then((res) => {
          console.log(res);
          this.$cookies.set("res", JSON.stringify(res));
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            let list = data.result.list;
            list.sort(this.sortAll("attendanceDate", true));
            let scheduleResultIdItemMap = {};
            list.forEach((element) => {
              console.log(element);
              let item = this.timelineItemTpl();
              let suffix = element.scheduleResultId ? "工作日" : "休息日";
              item.timestamp =
                this.$moment(element.attendanceDate).format("YYYY-MM-DD") +
                suffix;
              item.timeLineList.push({
                status: "being",
                timestamp: element.startTime,
                info: "实际上班点",
              });
              item.timeLineList.push({
                status: "being",
                timestamp: element.endTime,
                info: "实际下班点",
              });
              item.timeLineList.push({
                status: "waiting",
                timestamp: element.originalStartTime,
                info: "规定上班点",
              });
              item.timeLineList.push({
                status: "waiting",
                timestamp: element.originalEndTime,
                info: "规定下班点",
              });
              if (element.punchRecord) {
                let punchRecords = element.punchRecord.split(",");
                punchRecords.forEach((rec, idx) => {
                  item.timeLineList.push({
                    status: "finish",
                    timestamp: rec,
                    info: "打卡点" + idx,
                  });
                });
              }
              // 查询该班值的C点
              if (element.scheduleResultId) {
                scheduleResultIdItemMap[element.scheduleResultId] = item;
              }
              this.activities.push(item);

              console.log("排序前:", item.timeLineList);
              item.timeLineList.sort(this.sortAll("timestamp", true));
              console.log("排序后:", item.timeLineList);
            });
            return this.queryBanZhi(scheduleResultIdItemMap);
          }
        })
        .then((map) => {
          console.log(map);
          for (var key in map) {
            console.log(key, map[key]);
            let item = map[key];
            let url = this.$Url.serviceUrl.queryBanZhi + key;
            this.$get(url)
              .then((res) => {
                if (res && res.status == 200 && res.data) {
                  let data = res.data;
                  console.log(data);
                  let result = data.result;
                  if (result) {
                    item.timeLineList.push({
                      status: "timeOut",
                      timestamp: result.endEffTime,
                      info: "下班C点",
                    });
                    item.timeLineList.push({
                      status: "timeOut",
                      timestamp: result.startEffTime,
                      info: "上班C点",
                    });
                  }
                }
                item.timeLineList.sort(this.sortAll("timestamp", true));
              })
              .catch((res) => {
                console.log(res);
                this.openProcessLoading = false;
              });
          }
        });
    },
    getApplies() {
      let url = this.$Url.serviceUrl.queryApplys;
      let params = {
        params: {
          isInit: 0,
          userIds: [this.inputModel.userId],
          applyStartDate: null,
          applyEndDate: null,
          requestStartDate:
            this.$moment(this.requestDateRangeArr[0]).format("YYYY-MM-DD") +
            " 00:00:00",
          requestEndDate:
            this.$moment(this.requestDateRangeArr[1]).format("YYYY-MM-DD") +
            " 23:59:59",
          requestTypes: [this.selectedValue],
          approvalStates: null,
          requestNo: null,
        },
        page: 1,
        limit: 10,
      };
      return new Promise((resolve, reject) => {
        this.$post(url, params)
          .then((res) => {
            resolve(res);
          })
          .catch((res) => {
            console.log(res);
            reject(res);
          });
      });
    },
    queryApplys() {
      if (!this.inputModel.workNo) {
        this.$message.error("请输入工号!");
        return;
      }
      if (!this.inputModel.token) {
        this.$message.error("请输入token!");
        return;
      }
      if (!this.requestDateRangeArr || this.requestDateRangeArr.length == 0) {
        this.$message.error("请输入单据查询时间!");
        return;
      }
      this.$cookies.set("token", this.inputModel.token);
      this.getUserInfo()
        .then((res) => {
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            let records = data.result.records;
            if (records && records.length > 0) {
              let user = records[0];
              this.inputModel.userId = user.id;
            } else {
              this.$message.error("查无此人记录!");
            }
          }
          return this.getApplies();
        })
        .then((res) => {
          if (res && res.status == 200 && res.data) {
            let data = res.data;
            let list = data.result.list;
            if (list.length > 0) {
              this.tableData = [];
              list.forEach((elem) => {
                this.tableData.push(elem);
              });
            }
          }
        });
    },
    clear() {
      this.inputModel.token = "";
      this.inputModel.workNo = "";
      this.dateRangeArr = undefined;
    },
    timelineItemTpl() {
      return {
        timestamp: "x月y日",
        timeLineList: [],
      };
    },
    sortAll(property, bol) {
      return function(a, b) {
        var value1 = a[property];
        var value2 = b[property];
        if (bol) {
          // 升序
          return Date.parse(value1) - Date.parse(value2);
        } else {
          // 降序
          return Date.parse(value2) - Date.parse(value1);
        }
      };
    },
    validateParam() {
      if (!this.inputModel.token) {
        this.$message.error("token不能为空!");
        return false;
      }
      if (!this.inputModel.workNo) {
        this.$message.error("workNo不能为空!");
        return false;
      }
      console.log("dateRangeArr", this.dateRangeArr);
      if (!this.dateRangeArr || this.dateRangeArr.length == 0) {
        this.$message.error("请选择查询时间");
        return false;
      }
      return true;
    },
    clearPage() {
      this.activities = [
        {
          timestamp: "4月5日",
          timeLineList: [
            {
              status: "finish",
              timestamp: "16：00",
              info: "占个坑",
            },
            {
              status: "finish",
              timestamp: "18：00",
              info: "占个坑",
            },
          ],
        },
      ];
    },
  },
};
</script>

<style scoped lang="less">
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
  width: 100%;
}
a {
  color: #42b983;
}
// .main-wrapper{
//     background-color: #fff;
// }
.processInfo {
  background-color: #fff;
}
.timeLineTitle {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */

  .timeLineItem {
    display: flex;
    padding: 20px;
    font-size: 12px;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
  }
  .timeLineStatus {
    width: 12px;
    height: 10px;
    margin: 10px;
    border-radius: 2px;
  }
  .finish {
    background-color: #65bdaf;
  }
  .being {
    background-color: #eabd60;
  }
  .waiting {
    background-color: #e2e9f9;
  }
  .timeOut {
    background-color: #ce3820;
  }
}
</style>
<style lang="less">
.processInfo {
  overflow: auto;
  height: 100%;
  .el-timeline-item {
    padding-bottom: 120px;
  }
  .el-timeline-item__timestamp.is-top {
    position: absolute;
    left: -50px;
    color: #205081;
    /* font-weight: bold; */
    font-family: zcool-gdh;
    font-size: 12px;
  }
  .el-timeline-item__wrapper {
    padding: 0px 15px;
  }
  //   .timeLineDate .el-timeline-item:last-child .el-timeline-item__tail{
  //       display: none;

  //   }
}
</style>
